package configs

import (
	"fmt"
	"github.com/glebarez/sqlite"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type DBMode string

const (
	DBModeMysql  = "mysql"
	DBModeSqlite = "sqlite"
	DBModePgsql  = "pgsql"
)

type DB struct {
	Mode     DBMode `yaml:"mode"`
	DbName   string `yaml:"db_name"`
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
}

func (db DB) Dsn() gorm.Dialector {
	switch db.Mode {
	case DBModeMysql:
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			db.User,
			db.Password,
			db.Host,
			db.Port,
			db.DbName,
		)
		return mysql.Open(dsn)
	case DBModeSqlite:
		return sqlite.Open(db.Host)
	case DBModePgsql:
		zap.S().Warnf("不支持Pgsql,想用记得配置一下～～～")
	default:
		zap.S().Warnf("未配置数据库连接")
		return nil
	}
	return nil
}
